import { register } from "@midwayjs/esrun";
import { getProjectRoot } from "@midwayjs/hooks/internal";
import { resolve } from "path";
import { createServer, InlineConfig, mergeConfig } from "vite";
import { config as userConfig } from "./config.js";
import { getUnOccupiedPort } from "../node/network";
import killPort from "cross-port-killer";
import type { ServerOptions, ServerResult } from "./interfaces";

async function start({
  port = 8080,
  root,
  portMode,
}: ServerOptions): Promise<ServerResult> {
  register();
  root = root ? resolve(root) : getProjectRoot();

  if (portMode === "change-when-occupied") {
    port = await getUnOccupiedPort(port);
  }
  if (portMode === "kill-when-occupied") {
    try {
      killPort(port);
    } catch (error) {
      //
    }
  }

  process.env.MIDWAY_HTTP_PORT = `${port}`;

  const defaultConfig: InlineConfig = {
    root,
    configFile: false,
    server: { port },
    plugins: [require("@midwayjs/hooks-bundler").vite()],
  };
  // @ts-ignore
  const config = mergeConfig(defaultConfig, userConfig?.vite);
  const server = await createServer(config);
  await server.listen();
  server.printUrls();
  return { port };
}

export default start;
